import { ApiResponse, Suggestion, SearchResult } from '@/types/data'
import { RootThunkAction, SearchAction } from '@/types/store'
import { setHistory } from '@/utils/storage'
import request from '@/utils/request'

// 获取推荐
export const getSuggestion = (value: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ options: Suggestion }>>(
      '/suggestion',
      {
        params: {
          q: value,
        },
      }
    )
    dispatch({ type: 'search/suggestion', payload: res.data.data.options })
  }
}
// 添加历史记录
export const addHistory = (keyword: string): RootThunkAction => {
  return async (dispatch, getState) => {
    // 获取到原来的histories
    let histories = getState().search.histories
    // 1. 不允许有重复的历史记录, 先删除原来历史记录中的keyword
    histories = histories.filter((item) => item !== keyword)
    // 添加keyword
    histories = [keyword, ...histories]
    // 最多显示10条
    if (histories.length > 10) {
      histories = histories.slice(0, 10)
    }
    // 保存 redux
    dispatch({
      type: 'search/saveHistories',
      payload: histories
    })
    // 保存到本地
    setHistory(histories)
  }
}

// 清空历史记录-全部
export const clearHistory = (): SearchAction => {
  return {
    type: 'search/saveHistories',
    payload: []
  }
}

// 清除历史记录-单条
export const removeHistory = (keyword: string): RootThunkAction => {
  return async (dispatch, getState) => {
    let { histories } = getState().search
    // 判断keyword在histories是否存在，如果存在，应该删除
    histories = histories.filter((item) => item !== keyword)
    dispatch({
      type: 'search/saveHistories',
      payload: histories
    })
  }
}


// 获取搜索结果数据
export const getSearchResult = (
  keyword: string,
  page = 1,
  per_page = 10
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<SearchResult>>('/search', {
      params: {
        page,
        per_page,
        q: keyword
      }
    })
    dispatch({
      type: 'search/saveHistoryResult',
      payload: res.data.data
    })
  }
}

